package logic

import (
	"context"
	"errors"
	"registers/model/cache"
	"registers/model/mysql"
	"registers/pkg"

	"registers/registersrpc/internal/svc"
	"registers/registersrpc/registersrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 用户注册
func (l *RegisterLogic) Register(in *registersrpc.RegisterRequest) (*registersrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	err := user.FindUserByAccount(mysql.DB, in.Account)
	if err != nil {
		return nil, errors.New("该账号已存在")
	}

	user = mysql.User{
		Account:  in.Account,
		Password: pkg.Md5(in.Password),
	}
	err = user.Register(mysql.DB)
	if err != nil {
		return nil, err
	}

	//短信验证码
	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Account).Result()
	if result != in.Mobile {
		return nil, errors.New("短信验证码错误")
	}

	//图片验证码
	Captcha, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Account).Result()
	if Captcha != in.CaptchaImage {
		return nil, errors.New("图片验证码错误")
	}

	return &registersrpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
